package com.liming.payment.service.impl;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liming.common.exception.BusinessException;
import com.liming.common.pojo.dto.payment.PaymentUpdateDTO;
import com.liming.common.pojo.dto.payment.PrepayDTO;
import com.liming.common.pojo.entity.payment.Payment;
import com.liming.common.util.mybatisplus.MPUtil;
import com.liming.payment.mapper.PaymentMapper;
import com.liming.payment.service.PaymentMircoService;
import com.liming.service.wx.WxClient;
import com.liming.service.wx.pojo.vo.PrepayVO;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

/**
 * @author liming
 * @date 2025/4/8
 */
@Slf4j
@Service
@AllArgsConstructor
public class PaymentMircoServiceImpl extends ServiceImpl<PaymentMapper, Payment>
        implements PaymentMircoService, MPUtil<Payment> {

    private final WxClient wxClient;

    @Override
    public PrepayVO wxRepay(Long orderId) {
        Payment payment = lambdaQuery().eq(Payment::getOrderId, orderId).one();
        Assert.notNull(payment, () -> new BusinessException("支付记录不存在"));
        String prepayPackage = payment.getPrepayPackage();
        PrepayVO prepayVO = wxClient.wxJsapiRepay(prepayPackage);
        prepayVO.setOrderId(orderId);
        prepayVO.setOrderNo(payment.getOrderNo());
        return prepayVO;
    }

    @Override
    public Boolean wxPrepay(PrepayDTO prepayDTO) {
        Payment payment = new Payment();
        BeanUtils.copyProperties(prepayDTO, payment);
        Assert.isTrue(save(payment), "支付记录（预支付）保存失败");
        return true;
    }

    @Override
    public Boolean updateByOrderId(PaymentUpdateDTO paymentUpdateDTO) {
        return lambdaUpdate()
                .eq(Payment::getOrderId, paymentUpdateDTO.getOrderId())
                .set(Payment::getTransactionId, paymentUpdateDTO.getTransactionId())
                .set(Payment::getStatus, paymentUpdateDTO.getStatus())
                .update();
    }

}
